package com.mutouren.modules.datapush.web;

import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mutouren.common.log.LogAlias;
import com.mutouren.common.log.LogManager;
import com.mutouren.common.log.Logger;
//import com.mutouren.modules.datapush.base.DataPushLogAlias;
import com.mutouren.modules.datapush.config.ConfigManager;
import com.mutouren.modules.datapush.config.ConfigUpdateType;

@Controller
@RequestMapping(value = { "/api" }, method = {
		org.springframework.web.bind.annotation.RequestMethod.GET,
		org.springframework.web.bind.annotation.RequestMethod.POST })
public class DataPushAction {
	
	private final static Logger runLogger = LogManager.getLogger(LogAlias.SystemRun.name());
	private final static Logger errorLogger = LogManager.getLogger(LogAlias.SystemError.name());	
//	private final static Logger ReceiveLogger = LogManager.getLogger(DataPushLogAlias.DataPushReceive.name());
	
/*	@Resource
	private ServerProxy serverProxy;	
	
	@RequestMapping({ "/send" })
	public void send(HttpServletRequest request, HttpServletResponse response) throws IOException {		
		String result = "ok";
		String body = "";
		try {
			byte[] temp = toByteArray(request);
			PushMessage message = PushMessage.decode(temp);
			body = JsonUtils.beanToJson(message);
			boolean isSuccess = serverProxy.receive(message);
			if (isSuccess == false) {
				result = "fail: out of maxPermitSize";
			}
		} catch(Throwable t) {
			result = "fail";
			errorLogger.error("DataPushAction send error", t);
		} finally {
			writeReceiveLog(request, body);	
		}
		
		// 返回
		writeToResponse(response, result);	
	}*/
	
	@RequestMapping({ "/config" })
	public void config(String updateType, HttpServletRequest request, HttpServletResponse response) throws IOException {		
		String result = "ok";
		try {
			ConfigUpdateType type = ConfigUpdateType.toConfigUpdateType(NumberUtils.toByte(updateType, (byte)100));
			
			if (type == null) {
				result = "updateType params error, should between 0 and 2";	
			} else {
				ConfigManager.updateConfig(type);				
			}									
		} catch(Throwable t) {
			result = "fail";
			errorLogger.error("DataPushAction config error", t);
		} finally {
			writeLog(request, "");	
		}
		
		// 返回
		writeToResponse(response, result);	
	}
	
/*	private static void writeReceiveLog(HttpServletRequest request, String content) {
		String url = request.getRequestURL() + "?" + request.getQueryString();
		String ip = request.getRemoteAddr();
		String head = parseHead(request);
		String method = request.getMethod();
		String protocol =  request.getProtocol();
		
		String log = String.format("%s %s %s\r\n%s\r\n%s\r\n%s", protocol, method, url, ip, head, content);
		ReceiveLogger.info(log);
	}*/		
	
	private static void writeLog(HttpServletRequest request, String content) {
		String url = request.getRequestURL() + "?" + request.getQueryString();
		String ip = request.getRemoteAddr();
		String head = parseHead(request);
		String method = request.getMethod();
		String protocol =  request.getProtocol();
		
		String log = String.format("%s %s %s\r\n%s\r\n%s\r\n%s", protocol, method, url, ip, head, content);
		runLogger.info(log);
	}	
	
	private static String parseHead(HttpServletRequest request) {
		StringBuilder sbResult = new StringBuilder();
		@SuppressWarnings("rawtypes")
		Enumeration headerNames = request.getHeaderNames();
	    while (headerNames.hasMoreElements()) {
	        String key = (String) headerNames.nextElement();
	        String value = request.getHeader(key);
	        sbResult.append(String.format("%s:%s\r\n", key, value));
	    }
	    return sbResult.toString();
	}	
	
//	private static byte[] toByteArray(HttpServletRequest request) throws IOException {
//		return IOUtils.toByteArray(request.getInputStream());
//	}	
	
	private static void writeToResponse(HttpServletResponse response, String value) {
		response.setContentType("text/plain;charset=utf-8");
		try {
			response.getOutputStream().write(value.getBytes("utf-8"));
		} catch (Exception e) {
			errorLogger.error("DataPushAction writeToResponse error", e);
		}
	}		
}

